package com.project.controller;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.project.bean.SupplierBean;
import com.project.service.ISupplierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@RequestMapping("supplier")
@RestController
public class SupplierController {
    @Autowired
    private ISupplierService supplierService;

    @RequestMapping("findByItem")
    public IPage<SupplierBean> findByItem(Integer pageNO, String scope, String name) {
        return supplierService.findByItem(pageNO, scope, name);
    }

    @RequestMapping("findById")
    public SupplierBean findById(Integer id) {
        return supplierService.findById(id);
    }

    @RequestMapping("update")
    public String update(Integer supplierId, String newHeadName, String newPhone) {
        supplierService.update(supplierId, newHeadName, newPhone);
        return "success";
    }

    @RequestMapping("add")
    public String add(SupplierBean supplierBean) {
        if (supplierBean.getSupplierName() == null || supplierBean.getHeadName() == null || supplierBean.getHeadPhone() == null || supplierBean.getAddress() == null || supplierBean.getScope() == null) {
            return "error";
        }
        supplierService.add(supplierBean);
        return "success";
    }

    @RequestMapping("batchAdd")
    public String batchAdd(MultipartFile excelFile) throws Exception {
        if (excelFile != null) {
            if (excelFile.isEmpty() == false) {
                //设置初始化信息
                ImportParams params = new ImportParams();
                //设置选项卡
                params.setSheetNum(1);
                //设置标题栏占用的行数
                params.setTitleRows(0);
                //设置表头占用的行数
                params.setHeadRows(1);
                //读取上传文件的信息，封装为实体对象集合
                //第一个参数为上传文件的二进制流，
                //第二个参数为封装实体类的类模板
                //第三个参数为初始化信息
                List<SupplierBean> list = ExcelImportUtil.importExcel(excelFile.getInputStream(), SupplierBean.class, params);
                System.out.println(list);
                supplierService.batchAdd(list);
                return "success";
            }
        }
        return "error";
    }

    @RequestMapping("findAll")
    public List<SupplierBean> findAll() {
        return supplierService.findAll();
    }
}
